// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ExecutionContextCommandGroup.cs" company="Open Trader">
//   Copyright (c) David Denis (david.denis@systemathics.com)
// </copyright>
// <summary>
//   |  Open Trader - The Open Source Systematic Trading Platform
//   |
//   |  This program is free software: you can redistribute it and/or modify
//   |  it under the terms of the GNU General Public License as published by
//   |  the Free Software Foundation, either version 2 of the License, or
//   |  (at your option) any later version.
//   |
//   |  This program is distributed in the hope that it will be useful,
//   |  but WITHOUT ANY WARRANTY; without even the implied warranty of
//   |  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   |  GNU General Public License for more details.
//   |
//   |  You should have received a copy of the GNU General Public License
//   |  along with this program.  If not, see http://www.gnu.org/licenses
//   |
//   |  Up to date informations about Open Trader can be found at :
//   |    http://opentrader.org
//   |    http://opentrader.codeplex.com
//   |
//   |  For professional services, please visit us at :
//   |    http://www.systemathics.com
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Org.OpenTrader.Framework.CommandGroups
{
    #region Using Directives

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;

    using Org.OpenTrader.Framework.Entities;
    using Org.OpenTrader.Framework.Interfaces.UI;
    using Org.OpenTrader.Framework.LiveObjects;
    using Org.OpenTrader.Framework.LiveObjects.Interfaces;

    #endregion

    /// <summary>
    /// The execution context command group.
    /// </summary>
    public class ExecutionContextCommandGroup : CommandGroup
    {
        #region Constants and Fields

        /// <summary>
        /// The commands.
        /// </summary>
        private readonly IDictionary<string, Command> commands;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ExecutionContextCommandGroup"/> class.
        /// </summary>
        public ExecutionContextCommandGroup()
        {
            this.commands = new Dictionary<string, Command>();

            Command cmd;

            cmd = new ListCommand(this);
            this.commands[cmd.Name] = cmd;

            cmd = new RunCommand(this);
            this.commands[cmd.Name] = cmd;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets Commands.
        /// </summary>
        public override IDictionary<string, Command> Commands
        {
            get
            {
                return this.commands;
            }
        }

        /// <summary>
        /// Gets Help.
        /// </summary>
        public override string Help
        {
            get
            {
                return "This command group is used to handle execution contexts";
            }
        }

        /// <summary>
        /// Gets Name.
        /// </summary>
        public override string Name
        {
            get
            {
                return "execution_context";
            }
        }

        #endregion

        /// <summary>
        /// The list command.
        /// </summary>
        public class ListCommand : Command
        {
            private static readonly Identity Identity = Identity.Create(System.Reflection.MethodBase.GetCurrentMethod());

            #region Constructors and Destructors

            /// <summary>
            /// Initializes a new instance of the <see cref="ListCommand"/> class.
            /// </summary>
            /// <param name="commandGroup">
            /// The command group.
            /// </param>
            public ListCommand(CommandGroup commandGroup)
                : base(commandGroup)
            {
            }

            #endregion

            #region Properties

            /// <summary>
            /// Gets Help.
            /// </summary>
            public override string Help
            {
                get
                {
                    return "list known execution contexts";
                }
            }

            /// <summary>
            /// Gets Name.
            /// </summary>
            public override string Name
            {
                get
                {
                    return "list";
                }
            }

            /// <summary>
            /// Gets Usage.
            /// </summary>
            public override string Usage
            {
                get
                {
                    return string.Format("{0} {1}", this.CommandGroup.Name, this.Name);
                }
            }

            #endregion

            #region Public Methods

            /// <summary>
            /// The execute.
            /// </summary>
            /// <param name="args">
            /// The args.
            /// </param>
            /// <returns>
            /// </returns>
            public override Status Execute(string[] args)
            {
                var contexts = DBExecutionContextHelpers.GetExecutionContexts();

                Console.WriteLine("Listing execution contexts");

                foreach (var context in contexts)
                {
                    var name = context.Key;
                    var dbContext = context.Value;
                    Console.WriteLine(string.Format("{0,-20} {1}", name, dbContext.ID));
                }

                return Status.Success(Identity);
            }

            #endregion
        }

        /// <summary>
        /// The run command.
        /// </summary>
        public class RunCommand : Command
        {
            private static readonly Identity Identity = Identity.Create(System.Reflection.MethodBase.GetCurrentMethod());

            #region Constructors and Destructors

            /// <summary>
            /// Initializes a new instance of the <see cref="RunCommand"/> class.
            /// </summary>
            /// <param name="commandGroup">
            /// The command group.
            /// </param>
            public RunCommand(CommandGroup commandGroup)
                : base(commandGroup)
            {
            }

            #endregion

            #region Properties

            /// <summary>
            /// Gets Help.
            /// </summary>
            public override string Help
            {
                get
                {
                    return "run the given execution_context, using ui_provider_assembly to look for the UI";
                }
            }

            /// <summary>
            /// Gets Name.
            /// </summary>
            public override string Name
            {
                get
                {
                    return "run";
                }
            }

            /// <summary>
            /// Gets Usage.
            /// </summary>
            public override string Usage
            {
                get
                {
                    return string.Format("{0} {1} context_name ui_provider_assembly", this.CommandGroup.Name, this.Name);
                }
            }

            #endregion

            #region Public Methods

            /// <summary>
            /// The execute.
            /// </summary>
            /// <param name="args">
            /// The args.
            /// </param>
            /// <returns>
            /// </returns>
            public override Status Execute(string[] args)
            {
                if (args.Length < 2)
                {
                    return Status.Failure(Identity, "parameter context_name or ui_provider_assembly is missing");
                }

                Console.WriteLine(string.Format("Running context {0} using {1} to look for the UI", args[0], args[1]));

                var contextName = args[0];
                var assemblyName = args[1];

                // Application to run
                IApplication application = null;

                // Provider for the UI
                IUIProvider provider = null;

                try
                {
                    var a = Assembly.Load(assemblyName);
                    var types = from t in a.GetTypes() where Reflection.ImplementsInterface(t, typeof(IUIProvider).FullName) select t;
                    if (types.Count() != 1)
                    {
                        // no provider or more than 1
                        return Status.Failure(Identity, string.Format("Found {0} UI providers, must find 1 and only 1", types.Count()));
                    }

                    provider = Activator.CreateInstance(types.First()) as IUIProvider;
                }
                catch
                {
                }

                // No provider available
                if (provider == null)
                {
                    return Status.Failure(
                        Identity, string.Format("Unable to create an instance of any {0} implementor{0}", typeof(IUIProvider).FullName));
                }

                // Starting
                var openSplash = provider.CreateSplashUI(() => DBExecutionContextHelpers.Load(contextName, out application), "Starting " + contextName);
                openSplash.Run();

                // Running
                if (application != null)
                {
                    // Activate application
                    (application as Application).Activate();

                    // Run application until RootControl.ContainingForm is closed
                    var rootControl = provider.CreateApplicationUI(application);
                    rootControl.Run(contextName);

                    // Desactivate application
                    (application as Application).Desactivate();
                }

                // Stopping
                var closeSplash = provider.CreateSplashUI(() => DBExecutionContextHelpers.Unload(), "Stopping " + contextName);
                closeSplash.Run();

                return Status.Success(Identity);
            }

            #endregion
        }
    }
}